/*
 * Copyright (C), 2002-2017, 苏宁易购电子商务有限公司
 * FileName: ExchangeActivityServiceImpl.java
 * Author:   15050536
 * Date:     2017年5月4日 下午3:57:08
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.sawp.service.impl.exchange;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suning.sawp.constants.ExchangeConstants;
import com.suning.sawp.constants.PromotionConstants;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.esb.QryActDetailRsp;
import com.suning.sawp.dto.esb.QryActDetailRsp.ActivityDetail;
import com.suning.sawp.exception.SawpException;
import com.suning.sawp.intf.dao.exchange.ExchangeActivityDao;
import com.suning.sawp.intf.exchange.ExchangeActivityService;
import com.suning.sawp.intf.promotion.PromotionCouponService;
import com.suning.sawp.po.exchange.ExchangeActivity;
import com.suning.sawp.po.exchange.ExchangeActivityRule;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 已旧换新活动部分service
 *
 * @author 15050536 石键平
 */
@Service
public class ExchangeActivityServiceImpl implements ExchangeActivityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExchangeActivityServiceImpl.class);

    @Autowired
    private ExchangeActivityDao exchangeActivityDao;

    @Autowired
    private PromotionCouponService promotionCouponService;

    public QueryResult<ExchangeActivity> queryActivityList(String code, String type) {

        String cityId = StringUtils.EMPTY;
        String storeCode = StringUtils.EMPTY;
        if (StringUtils.isNotEmpty(type)) {
            if (String.valueOf(NumberUtils.INTEGER_ZERO).equals(type)) {
                storeCode = code;
            } else {
                cityId = code;
            }
        }
        List<ExchangeActivity> exchangeActivityList = queryActivityListFromESB(cityId, storeCode);

        // 调促销中心查询活动列表
        QryActDetailRsp resp = promotionCouponService.queryProActivityList(cityId, ExchangeConstants.BONUS_TRIGER_ID,
                PromotionConstants.PROMOT_COUPON_RESCOUCE_EXCHANGE, storeCode);
        if (resp != null && PromotionConstants.SUCCESS.equals(resp.getRequestResult())) {
            List<ActivityDetail> activityList = resp.getActivityList();
            for (ActivityDetail act : activityList) {
                ExchangeActivity exchangeActivity = getExchangeActivityFromIntf(act);
                exchangeActivityList.add(exchangeActivity);
            }
        }
        // 查询库里面配置过的进行中的活动
        List<ExchangeActivity> activitysInDB = exchangeActivityDao.queryActivityList();
        compareAndFill(exchangeActivityList, activitysInDB);
        QueryResult<ExchangeActivity> result = new QueryResult<ExchangeActivity>();
        result.setRecords(exchangeActivityList);
        result.setTotalSize(exchangeActivityList.size());
        return result;
    }

    /**
     * 
     * 调促销中心查询活动列表<br/>
     * 如果传了门店就调用37,38<br/>
     * 如果传了城市就调用31
     * 
     * @param cityId
     * @param storeCode
     * @return
     */
    private List<ExchangeActivity> queryActivityListFromESB(String cityId, String storeCode) {
        Set<ActivityDetail> activitys = new HashSet<ActivityDetail>();
        if (StringUtils.isNotEmpty(storeCode)) {
            // 调促销中心查询活动列表
            QryActDetailRsp resp = promotionCouponService.queryProActivityList(StringUtils.EMPTY,
                    ExchangeConstants.BONUS_TRIGER_ID, PromotionConstants.PROMOT_COUPON_RESCOUCE_OFFLINE_STORE,
                    storeCode);
            if (resp != null && PromotionConstants.SUCCESS.equals(resp.getRequestResult())) {
                List<ActivityDetail> list = resp.getActivityList();
                activitys.addAll(list);
            }
            resp = promotionCouponService.queryProActivityList(StringUtils.EMPTY, ExchangeConstants.BONUS_TRIGER_ID,
                    PromotionConstants.PROMOT_COUPON_RESCOUCE_OFFLINE_MARKET, storeCode);
            if (resp != null && PromotionConstants.SUCCESS.equals(resp.getRequestResult())) {
                List<ActivityDetail> list = resp.getActivityList();
                activitys.addAll(list);
            }
        } else if (StringUtils.isNotEmpty(cityId)) {
            QryActDetailRsp resp = promotionCouponService.queryProActivityList(cityId,
                    ExchangeConstants.BONUS_TRIGER_ID, PromotionConstants.PROMOT_COUPON_RESCOUCE_EXCHANGE,
                    StringUtils.EMPTY);
            if (resp != null && PromotionConstants.SUCCESS.equals(resp.getRequestResult())) {
                List<ActivityDetail> list = resp.getActivityList();
                activitys.addAll(list);
            }
        }
        List<ExchangeActivity> exchangeActivityList = new ArrayList<ExchangeActivity>();
        for (ActivityDetail act : activitys) {
            ExchangeActivity exchangeActivity = getExchangeActivityFromIntf(act);
            exchangeActivityList.add(exchangeActivity);
        }
        return exchangeActivityList;
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param exchangeActivityList
     * @param activitysInDB
     */
    private void compareAndFill(List<ExchangeActivity> exchangeActivityList, List<ExchangeActivity> activitysInDB) {
        if (CollectionUtils.isEmpty(exchangeActivityList) || CollectionUtils.isEmpty(activitysInDB)) {
            return;
        }
        for (ExchangeActivity ea : exchangeActivityList) {
            for (ExchangeActivity eaInDB : activitysInDB) {
                if (ea.getActivityId().equals(eaInDB.getActivityId())) {
                    ea.setConfigEmployee(eaInDB.getConfigEmployee());
                    ea.setConfigTime(eaInDB.getConfigTime());
                    ea.setOrderStartTime(eaInDB.getOrderStartTime());
                    ea.setOrderEndTime(eaInDB.getOrderEndTime());
                    break;
                }
            }
        }
    }

    /**
     * 把从接口获取的数据，组装成ExchangeActivity对象
     */
    private ExchangeActivity getExchangeActivityFromIntf(ActivityDetail activityDetail) {
        ExchangeActivity exchangeActivity = new ExchangeActivity();
        exchangeActivity.setActivityId(activityDetail.getActivityId());
        exchangeActivity.setActivityName(activityDetail.getActivityName());
        exchangeActivity.setActivitySecretKey(activityDetail.getActivitySecretKey());
        exchangeActivity.setStartTime(activityDetail.getStartTime());
        exchangeActivity.setEndTime(activityDetail.getEndTime());
        return exchangeActivity;
    }

    @Transactional
    public ReturnMsg<String> saveRule(ExchangeActivity activity, String orderStatus[], String cateTypes[]) {
        LOGGER.debug("活动对象为:{}\n订单规则：{}\n品类规则：{}", activity, orderStatus, cateTypes);
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        try {
            // 保存或更新活动 replace into
            exchangeActivityDao.saveActivity(activity);
            // 删除老规则，保存新规则
            exchangeActivityDao.delActivityRulesByActivityId(activity.getActivityId());

            // 没有活动规则的时候，就不管理
            if (orderStatus != null && orderStatus.length > 0) {
                // 订单状态活动规则
                List<ExchangeActivityRule> osActivityRules = new ArrayList<ExchangeActivityRule>();
                for (String os : orderStatus) {
                    ExchangeActivityRule activityRule = new ExchangeActivityRule();
                    activityRule.setActivityId(activity.getActivityId());
                    activityRule.setConfigType(ExchangeConstants.RULE_ORDER_STATUS);
                    activityRule.setConfigValue(os);
                    osActivityRules.add(activityRule);
                }
                exchangeActivityDao.batchSaveActivityRule(osActivityRules);
            }
            // 没有品类规则的时候，就不管理
            if (cateTypes != null && cateTypes.length > 0) {
                // 品类活动规则
                List<ExchangeActivityRule> ctActivityRules = new ArrayList<ExchangeActivityRule>();
                for (String ct : cateTypes) {
                    ExchangeActivityRule activityRule = new ExchangeActivityRule();
                    activityRule.setActivityId(activity.getActivityId());
                    activityRule.setConfigType(ExchangeConstants.RULE_CATE);
                    activityRule.setConfigValue(ct);
                    ctActivityRules.add(activityRule);
                }
                exchangeActivityDao.batchSaveActivityRule(ctActivityRules);
            }
        } catch (Exception e) {
            LOGGER.error("保存活动规则异常", e);
            throw new SawpException("保存活动异常", e);
        }
        return returnMsg;
    }

    @SuppressWarnings("unchecked")
    public ReturnMsg<JSONObject> findActivityById(String activityId) {
        ReturnMsg<JSONObject> returnMsg = new ReturnMsg<JSONObject>();
        ExchangeActivity exchangeActivity = exchangeActivityDao.findActivityById(activityId);
        JSONObject json = new JSONObject();
        // 时间转换
        if (exchangeActivity != null) {
            String orderStartTime = exchangeActivity.getOrderStartTime();
            String orderEndTime = exchangeActivity.getOrderEndTime();
            if (orderStartTime != null && orderStartTime.length() > 10) {
                json.put("starttime", orderStartTime.substring(0, 10));
            }
            if (orderEndTime != null && orderEndTime.length() > 10) {
                json.put("endtime", orderEndTime.substring(0, 10));
            }
        } else {
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage("根据活动id查询到的对象为空");
            return returnMsg;
        }
        List<ExchangeActivityRule> activityRules = exchangeActivityDao.queryActivityRulesByActivityId(activityId);
        List<String> orderStatusRules = getRulesByType(activityRules, ExchangeConstants.RULE_ORDER_STATUS);
        List<String> cateTypeRules = getRulesByType(activityRules, ExchangeConstants.RULE_CATE);
        json.put("orderStatus", JSONArray.fromObject(orderStatusRules));
        json.put("cateType", JSONArray.fromObject(cateTypeRules));

        returnMsg.setData(json);
        return returnMsg;
    }

    private List<String> getRulesByType(List<ExchangeActivityRule> activityRules, Integer type) {
        List<String> subRules = new ArrayList<String>();
        if (CollectionUtils.isEmpty(activityRules)) {
            return subRules;
        }
        for (ExchangeActivityRule activityRule : activityRules) {
            if (activityRule.getConfigType().equals(type)) {
                subRules.add(activityRule.getConfigValue());
            }
        }
        return subRules;
    }
}
